<script setup>
import { Delete, Search } from "@element-plus/icons-vue";
import { ref } from "vue";
import { ElMessage,ElMessageBox } from "element-plus";
import { getAllOrdersService, updateOrderService, deleteOrderService } from "@/api/order"
import { sendEmailService } from '@/api/email'

const allOrders = ref([]);

const lookOrderDetail = ref({});

const lookOrderDetailVisible = ref(false);

const sendVerificationCodeDisabled = ref(false);

const inputVerificationCode = ref("");

const verificationCode = ref("");

const confirmOrderVisible = ref(false);

//分页条数据模型
const pageNum = ref(1); //当前页
const total = ref(20); //总条数
const pageSize = ref(3); //每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  getallOrders();
};
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  getallOrders();
};

const getallOrders = async() => {
    const params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
    };
    const result = await getAllOrdersService(params);
    total.value = result.data.total;
    allOrders.value = result.data.items;
}

getallOrders();

const lookDetail = async(row) => {
    lookOrderDetail.value = row;
    lookOrderDetailVisible.value = true;
}

const deleteDetail = async(row) => {
  //删除订单
  ElMessageBox.confirm("您确认要删除该订单了吗?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //确认了删除订单
      const result = await deleteOrderService(row);
      ElMessage({
        type: result.message !== "操作成功" ? "error" : "success",
        message:
          result.messagee !== "操作成功" ? result.message : "删除订单成功",
      });
      getallOrders();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户取消了删除订单",
      });
    });
}

const showConfirmDialog = (row) => {
    lookOrderDetail.value = row;
    confirmOrderVisible.value = true;
    sendVerificationCodeDisabled.value = false;
}

const sendVerificationCode = async() => {
  const result = await sendEmailService(lookOrderDetail.value.email);
  verificationCode.value = result.data;
  sendVerificationCodeDisabled.value = true;
}

const updateOrder = async() => {
  const now = new Date();
  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false, // 24小时制
    timeZone: 'Asia/Shanghai' // 设置时区为上海，即中国标准时间
  };
  const localTime = now.toLocaleString('sv-SE', options).replace(',', '');
  const data = {
    businessName: lookOrderDetail.value.businessName,
    goodsName: lookOrderDetail.value.goodsName,
    buyTime: lookOrderDetail.value.buyTime,
    arriveTime: localTime,
    status: "用户已确认收货",
  }
  await updateOrderService(data);
  lookOrderDetailVisible.value = false;
  getallOrders();
}

const verifyCode = async() => {
  if(inputVerificationCode.value === verificationCode.value) {
    const now = new Date();
    const options = {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false, // 24小时制
      timeZone: 'Asia/Shanghai' // 设置时区为上海，即中国标准时间
    };
    const localTime = now.toLocaleString('sv-SE', options).replace(',', '');
    const data = {
      "businessName": lookOrderDetail.value.businessName,
      "goodsName": lookOrderDetail.value.goodsName,
      "buyTime": lookOrderDetail.value.buyTime,
      "emailTime": localTime,
      "status": "商家还未发货",
      "customerName": null,
    }
    await updateOrderService(data);
    ElMessage({type: "success", message: "确认完成"});
    confirmOrderVisible.value = false;
    getallOrders();
  }else {
    ElMessage({type: "error", message: "验证码输入错误，请重试！"});
  }
}
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>我的订单</span>
      </div>
    </template>
    <!-- 订单列表 -->
    <el-table :data="allOrders" style="width: 100%">
      <el-table-column label="商品图像">
        <template #default="{ row }">
          <img :src=row.businessImage style="width: 100px; object-fit: cover;">
        </template>
      </el-table-column>
      <el-table-column
        label="商品名称"
        width="400"
        prop="goodsName"
      ></el-table-column>
      <el-table-column label="购买时间" prop="buyTime"> </el-table-column>
      <el-table-column label="状态" prop="status"></el-table-column>
      <el-table-column>
        <template #default="{ row }">
          <span v-if="!row.emailTime"> 
            <el-link @click="showConfirmDialog(row)">点我前去确认收货地</el-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Search" circle plain type="primary" @click="lookDetail(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteDetail(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
    <el-dialog
    v-model="lookOrderDetailVisible"
    title="订单详细信息"
    width="600px"
    align-center
  >  
    <el-timeline style="max-width: 600px">
    <el-timeline-item placement="top" color="#0bbd87">
      <el-card>
        <h4 v-if="lookOrderDetail.buyTime">用户已下单</h4>
        <h4 v-if="!lookOrderDetail.buyTime">用户还未下单</h4>
        <p v-if="lookOrderDetail.buyTime">下单时间：{{ lookOrderDetail.buyTime }}</p>
      </el-card>
    </el-timeline-item>
    <el-timeline-item placement="top" :color="lookOrderDetail.emailTime ? '#0bbd87' : 'primary'">
      <el-card>
        <h4 v-if="lookOrderDetail.emailTime">用户已经确认收货地等信息</h4>
        <h4 v-if="!lookOrderDetail.emailTime">用户还未确认收货地等信息</h4>
        <p v-if="lookOrderDetail.emailTime">用户确认收货地时间：{{ lookOrderDetail.emailTime }}</p>
      </el-card>
    </el-timeline-item>
    <el-timeline-item placement="top" v-if="lookOrderDetail.emailTime" :color="lookOrderDetail.shippingTime ? '#0bbd87' : 'primary'">
      <el-card>
        <h4 v-if="lookOrderDetail.shippingTime">商家已发货</h4>
        <h4 v-if="!lookOrderDetail.shippingTime">商家还未发货</h4>
        <p v-if="lookOrderDetail.shippingTime">商家发货时间：{{ lookOrderDetail.shippingTime }}</p>
      </el-card>
    </el-timeline-item>
    <el-timeline-item placement="top" v-if="lookOrderDetail.shippingTime" :color="lookOrderDetail.deliveryTime ? '#0bbd87' : 'primary'">
      <el-card>
        <h4 v-if="lookOrderDetail.deliveryTime">商品已经到达</h4>
        <h4 v-if="!lookOrderDetail.deliveryTime">商品还没开始派送</h4>
        <p v-if="lookOrderDetail.deliveryTime">商品到达时间：{{ lookOrderDetail.deliveryTime }}</p>
      </el-card>
    </el-timeline-item>
    <el-timeline-item placement="top" v-if="lookOrderDetail.deliveryTime" :color="lookOrderDetail.arriveTime ? '#0bbd87' : 'primary'">
      <el-card>
        <h4 v-if="lookOrderDetail.arriveTime">用户已确认收货</h4>
        <h4 v-if="!lookOrderDetail.arriveTime">用户还未确认收货</h4>
        <p v-if="lookOrderDetail.arriveTime">用户确认收货时间时间：{{ lookOrderDetail.arriveTime }}</p>
      </el-card>
    </el-timeline-item>
    </el-timeline>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateOrder" style="display: flex;justify-content: center;" v-if="lookOrderDetail.deliveryTime && !lookOrderDetail.arriveTime">确认收货</el-button>
        <el-button @click="lookOrderDetailVisible = false" style="display: flex;justify-content: center;">关闭</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="confirmOrderVisible"
    width="30%"
    title="发送电子邮件验证码确认收货信息"
    append-to-body
    >
        <div class="verification-code">
        <el-input
            v-model="inputVerificationCode"
            style="width: 200px; display: inline-block"
        />
        <el-button
            :disabled="sendVerificationCodeDisabled"
            @click="sendVerificationCode"
            style="margin-left: 10px"
        >
            发送验证码
        </el-button>
        <el-button @click="verifyCode">
            确认
        </el-button>
        </div>
    </el-dialog>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.dialog-footer {
    display: flex;
    justify-content: center;
}
</style>